#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use XML::Simple;
use Data::Dumper;
use MIME::Base64;
use DBI;



my $url = "http://hikaru.local/cgi-bin/ifootprints_backend.pl";
my $name = "kitsune";
my $en0_mac_address = "00:16:cb:8a:79:f3";
my $database_file = "/tmp/mt.s";
my $wip = '/usr/bin/wip.sh';
my $capture = '/usr/bin/openIsight_cl -filename ';
my $state = "aok";
my $report_rate = 300;
my $speak_rate = 0;
my $mac_id = 0;
my @phrases;
my $dbh;

my $server_error = 0;

create_db();

while(1){

	my $ua = LWP::UserAgent->new;
	$ua->agent("ifootprints/0.1 ");
	my $req = HTTP::Request->new(POST => $url);
	my $xml = '<?xml version="1.0" encoding="utf-8" ?><status type="check_in" name="' . $name . '" en0_mac_address="' . $en0_mac_address  . '" />';
	$req->content($xml);
	my $res = $ua->request($req);
	if ($res->is_success) {

		my $parser = new XML::Simple (ForceArray => 1);
		my $vars = $parser->XMLin($res->content);
		if(!exists($vars->{'type'})){
			$server_error = 1;
		}
		else{
			$server_error = 0;
		}
		if($vars->{'type'} eq "set_config"){
			$speak_rate 		= $vars->{'config'}->{'speak_rate'}->{'value'};
			$report_rate 		= $vars->{'config'}->{'report_rate'}->{'value'};
			$mac_id 		= $vars->{'config'}->{'mac_id'}->{'value'};
			@phrases		= split(/\|/, $vars->{'config'}->{'pipe_delimited_phrases'}->{'value'});
			$state 			= $vars->{'config'}->{'state'}->{'value'};
			$dbh->do("DELETE from config;");
			my $sth = $dbh->prepare("INSERT INTO config (mac_id, report_rate, speak_rate, pipe_delimited_phrases, state) VALUES (?, ?, ?, ?, ?);") or die "$!";
			$sth->execute($mac_id, $report_rate, $speak_rate, join('|', @phrases), $state) or die "$!";
			$sth->finish();

		}
		elsif($vars->{'type'} eq "created_new_entry"){
			next;
		}
		check_db();
	}
        else {
		print $res->status_line, "\n";
		my $sth = $dbh->prepare("SELECT * from config;");
		$sth->execute();
		if(my $row = $sth->fetchrow_hashref){

			$speak_rate             = $row->{'speak_rate'};
			$mac_id 	        = $row->{'mac_id'};
                        $report_rate            = $row->{'report_rate'};
                        @phrases                = split(/\|/, $row->{'pipe_delimited_phrases'});
                        $state                  = $row->{'state'};
			print "Loaded values from db\n";
		}
		else{
			print "Using defaults\n";
		}
		$sth->finish();
	}
	if($state eq "stolen"){
		my $file_name = "/tmp/" . time() . ".jpg";

		`$capture $file_name &> /dev/null`;
		open(IMAGE, $file_name);
		my $base_64 = "";
		while(<IMAGE>){
			$base_64 .= encode_base64($_);
		}

		my $airport = `airport -s`;
		$airport .= `ifconfig`;
		$airport .= `airport -I`;
		my $ip = `$wip`;
		chomp($ip);


		$airport = encode_base64($airport);

		my $xml = 
	'<?xml version="1.0" encoding="utf-8" ?>
	<status mac_id="' . $mac_id . '" type="track" name="' . $name . '" en0_mac_address="' . $en0_mac_address . '">
	<base_64_jpg_image value="' . $base_64 . '" />
	<airport_dump value="' . $airport  . '" />
	<ip_addresses value="' . $ip . '" />
	</status>';
		
		my $ua = LWP::UserAgent->new;
		$ua->agent("ifootprints/0.1 ");
		my $req = HTTP::Request->new(POST => $url);
		$req->content($xml);
		my $res = $ua->request($req);
		if(!$res->is_success or $server_error){
			my $sth = $dbh->prepare("INSERT INTO tracks (timestamp, mac_id, base_64_jpg_image, airport_dump, ip_addresses) VALUES (?, ?, ?, ?, ?);") or die "$!";
			print "Saving to db...\n";
			$sth->execute(time(), $mac_id, $base_64, $airport, $ip) or die "$!";
			$sth->finish();
		}
	}
	sleep($report_rate);
}

sub check_db
{
	my $sth = $dbh->prepare("SELECT * from tracks;");
	$sth->execute();
	while (my $row = $sth->fetchrow_hashref){
		my $xml =
'<?xml version="1.0" encoding="utf-8" ?>
<status mac_id="' . $mac_id . '" type="track" name="' . $name . '" en0_mac_address="' . $en0_mac_address . '">
        <base_64_jpg_image value="' . $row->{'base_64_jpg_image'} . '" />
        <airport_dump value="' . $row->{'airport_dump'}  . '" />
        <ip_addresses value="' . $row->{'ip_addresses'} . '" />
</status>';

		my $ua = LWP::UserAgent->new;
		$ua->agent("ifootprints/0.1 ");
		my $req = HTTP::Request->new(POST => $url);
		$req->content($xml);
		my $res = $ua->request($req);
		if($res->is_success){
			my $sth2 = $dbh->prepare("DELETE from tracks where id = ?;") or die "$!";
			$sth2->execute($row->{'id'});
			$sth2->finish();
		}
	}
	$sth->finish();

}

sub create_db
{
	open(OUTFILE, ">>$database_file") or die  . "$! -- Cannot create $database_file";
	close(OUTFILE);
	$dbh = DBI->connect("dbi:SQLite:dbname=$database_file","","",undef) or die $!;

	$dbh->do("CREATE TABLE IF NOT EXISTS `tracks` (`id` INTEGER PRIMARY KEY, `timestamp` INTEGER, `mac_id` INTEGER, `base_64_jpg_image` text, `airport_dump` text, `ip_addresses` text);") or die "$!";
	$dbh->do("CREATE TABLE IF NOT EXISTS `config` (`id` INTEGER PRIMARY KEY, `mac_id` INTEGER, `state` text, `report_rate` INTEGER, `speak_rate` INTEGER, `pipe_delimited_phrases` text);");
}

